'''
Created on 20 Dec 2010

@author: yusuf
'''
import ussd_api,sys,session
from datetime import datetime, timedelta

if __name__ == '__main__':
# Create a connection object to the USSD Access Point
    conn = ussd_api.UxmlConnect()
 
# Create a UXML PDU object
    pdu = ussd_api.UxmlPdu()
    try:
            #Perform a bind to USSD
            status = False
            cack = True
            m_port = 8000
            m_user = "ACC_T01"
            m_password  = "password"
            m_rsys = "ussdap_nl0\\@196.11.242.11";
            m_node = "node"
            m_cookie = "ussdgw"
            status = conn.connect(m_rsys , m_port , m_user, m_password, m_node, m_cookie, 5000 )
            if (status): print("Connected")
            else: print("Not connected")
# Setup control PDU
            lastCtrl = datetime.now()
            delay = timedelta(seconds=30)
            cpdu = ussd_api.UxmlPdu ()
            cpdu.setPdu("CTRL")
            cpdu.setReqid("0")
            cpdu.setTid("0")
            cpdu.setEncoding("ASCII")
            cpdu.setTariff("*")
            cpdu.setStatus("0")
            cpdu.setMsisdn("*")
            
            sessions =  {}

# Process requests from USSD
            while(status):
                result = conn.receivePdu ( pdu )
                if (result):
                    print("Received : " + pdu.getPdu() +" "+ pdu.getMsisdn() +" "+ pdu.getString() )
                    if (pdu.getPdu() == "PSSRR"):
                        sm = session.Session(conn, pdu.getMsisdn())
                        sm.start()
                        sm.respondMain(pdu)
                        sessions[pdu.getMsisdn()] = sm
                    elif ((pdu.getPdu()=="USSRC")or(pdu.getPdu()=="USSNC")):
                        if (not sessions.has_key(pdu.getMsisdn())):
                            sm = Session(conn, pdu.getMsisdn())
                            sm.start()
                            sessions[pdu.getMsisdn()] = sm
                        sm = sessions.get(pdu.getMsisdn())
                        sm.respond(pdu);
                    elif (pdu.getPdu()=="ABORT"):
                        try:
                            sm = sessions.get(pdu.getMsisdn())
                            sm.end()
                            sessions.pop(pdu.getMsisdn())
                        except: 
                            print(pdu.getString())
                        
                    elif (pdu.getPdu()=="CTRL"):
                        print("Received CTRL Ack")
                        cack=True;                
#  Reset the PDU
                    pdu.clearValues()
                    lastCtrl =  datetime.now()
                
# Send CTRL PDU
                if ((datetime.now() - lastCtrl)>delay):
                    if (cack):
                        lastCtrl =  datetime.now()
                        cpdu.setString(str(lastCtrl.strftime("%d-%m-%y %H:%M:%S")))
                        conn.send(cpdu)
                        cack=False
                    else: status=false
                
            
    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise
        
    


    